package com.distribute.application.api.rest.member;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.distribute.application.api.BaseApiController;
import com.distribute.application.api.utils.Arith;
import com.distribute.application.api.utils.DateUtils;
import com.distribute.application.api.utils.IpUtil;
import com.distribute.application.api.utils.PayUtil;
import com.distribute.application.api.utils.mobile.MobileCodeUtil;
import com.distribute.application.utils.WechatMouldUtil;
import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.title;
import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.model.Account;
import com.distribute.framework.model.Agent;
import com.distribute.framework.model.AgentCard;
import com.distribute.framework.model.AgentCardOrder;
import com.distribute.framework.model.AgentConf;
import com.distribute.framework.model.AgentConf.Products;
import com.distribute.framework.model.BrandAccount;
import com.distribute.framework.model.Commodity;
import com.distribute.framework.model.Configur;
import com.distribute.framework.model.Coupon;
import com.distribute.framework.model.DirectOrder;
import com.distribute.framework.model.IncomeRecord;
import com.distribute.framework.model.Member;
import com.distribute.framework.model.OfflineCoupon;
import com.distribute.framework.model.Product;
import com.distribute.framework.model.ProductDetails;
import com.distribute.framework.model.ProductOrder;
import com.distribute.framework.model.Region;
import com.distribute.framework.model.TbCardBinding;
import com.distribute.framework.model.TbMsg;
import com.distribute.framework.model.TbOrderInvoies;
import com.distribute.framework.model.TbPartnerCardOrder;
import com.distribute.framework.model.TbPartnerConfig;
import com.distribute.framework.model.TbPartnerConfig.TbpcProducts;
import com.distribute.framework.model.TbPartners;
@RestController(value="api.MemberAgentController")
public class MemberAgentController extends BaseApiController{
	/**
	 * 检测对品牌是否申请过代理
	 * @return
	 */
	@RequestMapping("/api/memberAgent/isApplyAgent.do")
	public @title("检测对品牌是否申请过代理") Protocol isApplyAgent(
			@title("品牌商编号") Long banrdId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		 Agent agent=Agent.where.member(member.getId()).merchant(banrdId).status((short)1).get();	
		 if (agent==null) {
				protocol.set("agentType", 0);
			}else {
				protocol.set("agentType", 1);//代理商
			}
		return protocol;
	}
	/**
	 * 用户绑定线下代理卡
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/memberAgent/agentLocalSave.do")
	public @title("用户绑定线下代理卡") Protocol agentLocalSave(
			@title("领取码") String codes,
			@title("品牌编号") Long banrdId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		AgentCard agentCard=AgentCard.where.merchant(banrdId).get();
		if (agentCard==null) {
			protocol.set("type", false);
			protocol.set("msg", "您的码有误");
			return protocol;
		}
		TbCardBinding cardBinding=TbCardBinding.where.tbcbReCode(codes).tbcbBrand(banrdId).get();
		if (cardBinding==null) {
			protocol.set("type", false);
			protocol.set("msg", "您的码有误");
			return protocol;
		}
		if (cardBinding.getTbcbBindState()==(short)1) {
			protocol.set("type", false);
			protocol.set("msg", "此卡已绑定过了");
			return protocol;
		}
		
		Agent agent=new Agent(
				banrdId//所属品牌 [非空]
			 	,member.getId()//关联会员 [非空]
			 	,member.getmTop()
   	            ,member.getmToptop()
			 	,new Date()//修改时间 [非空]
			 	,new Date()//添加时间 [非空]
			 	,(short)1//状态 [非空]
				);
		   agent.save();
		   cardBinding.setTbcbBindUser(member.getId());
		   cardBinding.setTbcbBindState((short)1);
		   cardBinding.update();
		    List<com.distribute.framework.model.AgentCard.Products> cProducts=agentCard.get$products();
		    if (cProducts.size()>0) {
				for (com.distribute.framework.model.AgentCard.Products products : cProducts) {
					  Commodity commodity=Commodity.where.id(products.getCommodity()).get();
					  Product product2=Product.where.merchant(banrdId).member(member.getId()).commodity(commodity.getId()).get();
						 if (product2==null) { 
					  Product product=new Product(
							        commodity.getName()//名称 [非空]
								 	,banrdId//品牌信息
								 	,member.getUid$()
								 	,member.getId()//所属会员
								 	,products.getCommodity()//商品信息
								 	,commodity.getPrice()
							        ,commodity.getUnit$()
								 	,commodity.getImage()
								 	,products.getNumber()//数量
								 	,0
								 	,""//规格属性
								 	,0//预留字段
								 	,"线下代理卡绑定"//来源描述
								 	,getThreeYear()
								 	,new Date()//修改时间 [非空]
								 	,new Date()//添加时间 [非空]
								 	,(short)1//状态 [非空]
									);
					   product.save();
				   }else {
						product2.setCount(product2.getNumber()+products.getNumber());
						product2.update();
				}
				}
			}
				protocol.set("type", true);
				protocol.set("msg", "绑定成功");
		return protocol;
	}
	private Date getThreeYear() {
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
        c.add(Calendar.YEAR, 3);
        Date y = c.getTime();
		return y;
	}
	/**
	 * 用户提交合伙人申请
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/memberAgent/HHRSave.do")
	public @title("用户提交合伙人申请") Protocol HHRSave(
			@title("formId") String formId,
			@title("订单号") String orderNo,
			@title("姓名*") String name,
			@title("手机号") String mobile,
			@title("性别") String sex,
			@title("年龄") String age,
			@title("收入") String sr,
			@title("职业") String zy,
			@title("纬度") String latitude,
			@title("经度") String longitude,
			@title("品牌商编号") Long banrdId,
			@title("地址编号") Long adressId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		Region region=Region.where.id(adressId).get();
				TbPartners tbPartners=new TbPartners(
						member.getId()//会员
					 	,banrdId//品牌
					 	,name//姓名
					 	,mobile//手机号
					 	,member.getmTop()
   	             	 	,member.getmToptop()
					 	,sex
					 	,age
					 	,sr
					 	,zy
					 	,region.getFullName()
					 	,adressId//街道地址
					 	,""//审核理由
					 	,longitude
					 	,latitude
					 	,region.get$parent().get$parent().get$parent().getId()
					 	,region.get$parent().get$parent().getId()
					 	,region.get$parent().getId()
					 	,new Date()//申请时间
						,(short)2//购买卡情况
					 	,(short)2//审核状态
					 	,new Date()
						);
				tbPartners=tbPartners.save();
				TbPartnerCardOrder partnerCardOrder=TbPartnerCardOrder.where.orderNumber(orderNo).get();
				partnerCardOrder.setHhrCard(tbPartners.getTbpId());
				partnerCardOrder.update();
				 WechatMouldUtil wechatMouldUtil=new WechatMouldUtil();
				 Map<String, Object> data=new HashMap<String, Object>();
				 Map<String, Object> data1=new HashMap<String, Object>();
				data1.put("value", "合伙人卡购买成功");
				data.put("keyword1", data1);
				Map<String, Object> data2=new HashMap<String, Object>();
				data2.put("value", region.getFullName());
				data.put("keyword2", data2);
				Map<String, Object> data3=new HashMap<String, Object>();
				data3.put("value", DateUtils.getTime());
				data.put("keyword3", data3);
             wechatMouldUtil.sendWechatmsgToUser(formId, "jl99X7ad0uB4HQrTJXWGStMv4UzYUDJOkH7FxBvm1jA", member.getOpenid(), data);//发送微信小程序消息模板
                
				//获取时间加一年或加一月或加一天
  	             Date date = new Date();
  	             Calendar cal = Calendar.getInstance();
  	             cal.setTime(date);//设置起时间
              cal.add(Calendar.YEAR, 1);//增加一年
  	            MobileCodeUtil.sendTextHhr(tbPartners.getTbpMobile(), tbPartners.getTbpJiedao$(), DateUtils.formatDateTime(cal.getTime()));
		return protocol;
	}
	/**
	 * 检测对品牌是否申请过合伙人
	 * @return
	 */
	@RequestMapping("/api/memberAgent/isApplyHHR.do")
	public @title("检测对品牌是否申请过合伙人") Protocol isApplyHHR(
			@title("品牌商编号") Long banrdId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		 Agent agent=Agent.where.member(member.getId()).merchant(banrdId).status((short)1).get();	
		 if (agent==null) {
				protocol.set("HHRType", 0);
			}else {
				protocol.set("HHRType", 1);//代理商
			}
		protocol.set("HHR", TbPartners.where.tbpMember(member.getId()).tbpBrand(banrdId).get());
		return protocol;
	}
	/**
	 * 根据品牌获取合伙人卡。
	 * @return
	 */
	@RequestMapping("/api/memberAgent/getBanrdOneHHRCard.do")
	public @title("根据品牌获取合伙人卡") Protocol getBanrdOneHHRCard(
			@title("品牌商编号") Long merchant
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		TbPartners agent=TbPartners.where.tbpBrand(merchant).tbpMember(member.getId()).tbpAuth((short)2).tbpPayCard((short)1).get();
		if (agent==null) {
			protocol.set("card", TbPartnerConfig.where.tbpcBrand(merchant).get()==null?null:TbPartnerConfig.where.tbpcBrand(merchant).get().toJSON());
		}else {
			protocol.set("card", null);
		}
		return protocol;
	}
	/**
	 * 根据品牌获取合伙人卡详情页。
	 * @return
	 */
	@RequestMapping("/api/memberAgent/getBanrdHHRDetails.do")
	public @title("根据品牌获取合伙人卡详情页") Protocol getBanrdHHRDetails(
			@title("品牌ID") Long banrdId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		TbPartnerConfig agentConf=TbPartnerConfig.where.tbpcBrand(banrdId).get();
		if (agentConf!=null) {
			Map map=agentConf.toJSON();
		  List<TbpcProducts> aList=	agentConf.get$tbpcProducts();
		  if (aList.size()>0) {
			  List<Map> list=new ArrayList<Map>();
				double sumDouble=0.0;
				for (TbpcProducts products : aList) {
					Map<String, Object> map2=new HashMap<String, Object>();
					Commodity commodity=Commodity.where.id(Long.valueOf(products.getGoods())).get();
					map2.put("goods", commodity==null?null:commodity.toJSON());
					map2.put("number", products.getNumber());
					map2.put("price", products.getPrice());
					if (commodity!=null) {
						sumDouble=Arith.round(Arith.add(sumDouble, Arith.round(Arith.mul(commodity.getPrice(), Double.valueOf(products.getNumber())), 2)), 2);
					}
				   list.add(map2);
				}
				map.put("sum", sumDouble);
				map.put("list", list);
		}else {
			map.put("list", null);
		}
			protocol.set("card", map);
		}else {
			protocol.set("card", null);
		}
		return protocol;
	}
	/**
	 * 根据品牌获取代理卡详情页。
	 * @return
	 */
	@RequestMapping("/api/memberAgent/getBanrdAgentDetails.do")
	public @title("根据品牌获取代理卡详情页") Protocol getBanrdAgentDetails(
			@title("品牌ID") Long banrdId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		AgentConf agentConf=AgentConf.where.merchant(banrdId).get();
		if (agentConf!=null) {
			Map map=agentConf.toJSON();
		  List<Products> aList=	agentConf.get$products();
		  if (aList.size()>0) {
			  List<Map> list=new ArrayList<Map>();
				double sumDouble=0.0;
				for (Products products : aList) {
					Map<String, Object> map2=new HashMap<String, Object>();
					Commodity commodity=Commodity.where.id(products.getCommodity()).get();
					map2.put("goods", commodity==null?null:commodity.toJSON());
					map2.put("number", products.getNumber());
					map2.put("price", commodity.getPrice());
					if (commodity!=null) {
						sumDouble=Arith.round(Arith.add(sumDouble, Arith.round(Arith.mul(commodity.getPrice(), products.getNumber()), 2)), 2);
					}
				   list.add(map2);
				}
				map.put("sum", sumDouble);
				map.put("list", list);
		}else {
			map.put("list", null);
		}
			protocol.set("card", map);
		}else {
			protocol.set("card", null);
		}
		return protocol;
	}
	
	/**
	 * 合伙人购买回调
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/memberAgent/payHeHuoRen.wx")
	public @title("代理卡购买回调") void payHeHuoRen(
			HttpServletRequest request,HttpServletResponse response
			)throws Exception{
		 BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));  
		  String line = null;  
	        StringBuilder sb = new StringBuilder();  
	        while((line = br.readLine()) != null){  
	            sb.append(line);  
	        }  
	        //sb为微信返回的xml  
	        String notityXml = sb.toString();  
	        String resXml = "";  
	        System.out.println("接收到的报文：是" + notityXml);  
	      
	        Map map = PayUtil.doXMLParse(notityXml);  
	         // System.out.println("返回ID"+map.get("out_trade_no"));
	        //  System.out.println("返回成功"+ map.get("return_code"));
	        if (map!=null){
	        	   String returnCode = (String) map.get("return_code");  
	   	        if("SUCCESS".equals(returnCode)){  
//	   	            //验证签名是否正确  
//	   	            if(PayUtil.verify(PayUtil.createLinkString(map), (String)map.get("sign"), WxPayConfig.key, "utf-8")){  
	   	                /**此处添加自己的业务逻辑代码start**/  
	   	                  String out_trade_no=(String) map.get("out_trade_no");
	   	               System.out.println("合伙人"+out_trade_no);
	   	               TbPartnerCardOrder order=TbPartnerCardOrder.where.orderNumber(out_trade_no).get();
	   	            	System.out.println("合伙人"+JSON.toJSONString(order));
   	    	//	   	            AgentCardOrder.where.id(order.getId()).payStatus(2,"<").set.payStatus((short)2).update();
	   	               if (order.getPayStatus()==(short)1) {
	   	                order.setPayStatus((short)2);
   	                    order.update();//修改订单
   	                 TbMsg msg=new TbMsg(
   	                		order.getMember()//会员
							 	,"合伙人购买成功"//内容
							 	,new Date()//时间
								);
						msg.save();
   	                 Configur configur=Configur.where.get();
   	              Member member=Member.where.uid(order.getMember()).get();
   	           System.out.println("用户信息人1"+out_trade_no);
   	                   TbPartnerConfig agentConf=TbPartnerConfig.where.tbpcBrand(order.getMerchant()).get();
   	                   if (agentConf!=null) {
						List<TbpcProducts> aList=agentConf.get$tbpcProducts();
						if (aList.size()>0) {
							 System.out.println("产品1"+JSON.toJSONString(aList));
							for (TbpcProducts products : aList) {
								Product product=Product.where.member(member.getId()).merchant(order.getMerchant()).commodity(Long.valueOf(products.getGoods())).get();
								if (product!=null) {
									Commodity commodity=Commodity.where.id(Long.valueOf(products.getGoods())).get();
									product.setNumber(product.getNumber()+Integer.valueOf(products.getNumber()));
									product.update();
									ProductDetails productDetails=new ProductDetails(
											"合伙人购买赠送"//获得方式
										 	,order.getMerchant()//品牌信息
										 	,member.getId()//所属会员
										 	,Long.valueOf(products.getGoods())//商品信息
										 	,Double.valueOf(commodity.getPrice())
										 	,Integer.valueOf(products.getNumber())//数量
										 	,0
										 	,0
										 	,new Date()//获得时间 [非空]
										 	,(short)1//状态 [非空]
											);
									productDetails.save();
								}else {
									Commodity commodity=Commodity.where.id(Long.valueOf(products.getGoods())).get();
									Product product2=new Product(
											commodity.getName()//名称 [非空]
										 	,order.getMerchant()//品牌信息
										 	,member.getUid$()
										 	,member.getId()//所属会员
										 	,Long.valueOf(products.getGoods())//商品信息
										 	,commodity.getPrice()
							                ,commodity.getUnit$()
										 	,commodity.getImage()
										 	,Integer.valueOf(products.getNumber())//数量
										 	,0
										 	,""//规格属性
										 	,0
										 	,"合伙人卡购买赠送"//来源描述
										 	,getThreeYear()
										 	,new Date()//修改时间 [非空]
										 	,new Date()//添加时间 [非空]
										 	,(short)1//状态 [非空]
											);
									product2.save();
									ProductDetails productDetails=new ProductDetails(
											"合伙人购买赠送"//获得方式
										 	,order.getMerchant()//品牌信息
										 	,member.getId()//所属会员
										 	,Long.valueOf(products.getGoods())//商品信息
										 	,Double.valueOf(commodity.getPrice())
										 	,Integer.valueOf(products.getNumber())//数量
										 	,0
										 	,0
										 	,new Date()//获得时间 [非空]
										 	,(short)1//状态 [非空]
											);
									productDetails.save();
									
								}
							}
						}
					}
   	                Double ptjj=0.0;
   	                Double ptzj=0.0; 
   	                Double dljj=0.0;
	                Double dlzj=0.0;  
   	                  if(member.gettTop()!=null&&!member.gettTop().equals("")){//
   	                	 Member member2=Member.where.uid(Long.parseLong(member.gettTop())).get();//上级//39
   	                	TbPartners agent=TbPartners.where.tbpMember(member2.getId()).tbpBrand(order.getMerchant()).tbpPayCard((short)2).get();
   	                	Agent agents=Agent.where.member(member2.getId()).merchant(order.getMerchant()).status((short)1).get();
   	                	Account account=Account.where.member(member2.getId()).get();
   	                	   if (agent!=null||agents!=null) {//代理商
   	                		   dlzj=Arith.mul(order.getPayMoney(), agentConf.getTbpcDlZhj());
   	                		IncomeRecord incomeRecord=new IncomeRecord(
   	                				agents!=null?(short)2:(short)3//用户身份
   	                				,(short)4//来源
   	                			 	,(short)1//收益类型
   	                			 	,Arith.mul(order.getPayMoney(), agentConf.getTbpcDlZhj())//贡献收益
   	                			 	,member.getHeader()//头像
   	                			 	,member.getNickName()//姓名
   	                			 	,member.getNickName()
   	                			 	,member2.getNickName()
   	                			 	,member.getId()//贡献人
   	                			 	,member2.getId()//收益人
   	                			 	,order.getOrderNumber()//订单编号
   	                			 	,order.getMerchant()//品牌信息
   	                			 	,(short)2//结算情况
   	                			 	,new Date()//修改时间 [非空]
   	                			 	,new Date()//添加时间 [非空]
   	                			 	,(short)1//状态 [非空]
   	                			 	);
   	                		incomeRecord.save();
   	                		account.setMoney(Arith.round(Arith.add(account.getMoney(), Arith.mul(order.getPayMoney(), agentConf.getTbpcDlZhj())), 2));
   	                		TbMsg msg2=new TbMsg(
   	                				member2.getId()//会员
   	     						 	,"您获得了收益:"+Arith.mul(order.getPayMoney(), agentConf.getTbpcDlZhj())//内容
   	     						 	,new Date()//时间
   	     							);
   	                		msg2.save();
   	                	   }else {//普通分销员
								ptzj=Arith.mul(order.getPayMoney(), agentConf.getTbpcPtZhj());
								IncomeRecord incomeRecord=new IncomeRecord(
										(short)1
										,(short)4//来源
	   	                			 	,(short)1//收益类型
	   	                			 	,Arith.mul(order.getPayMoney(), agentConf.getTbpcPtZhj())//贡献收益
	   	                			 	,member.getHeader()//头像
	   	                			 	,member.getNickName()//姓名
	   	                			 	,member.getNickName()
   	                			 	,member2.getNickName()
	   	                			 	,member.getId()//贡献人
	   	                			 	,member2.getId()//收益人
	   	                			 	,order.getOrderNumber()//订单编号
	   	                			 	,order.getMerchant()//品牌信息
	   	                			 	,(short)2//结算情况
	   	                			 	,new Date()//修改时间 [非空]
	   	                			 	,new Date()//添加时间 [非空]
	   	                			 	,(short)1//状态 [非空]
	   	                			 	);
	   	                		incomeRecord.save();
	   	                		account.setMoney(Arith.round(Arith.add(account.getMoney(), Arith.mul(order.getPayMoney(), agentConf.getTbpcPtZhj())), 2));
	   	                		TbMsg msg2=new TbMsg(
	   	                				member2.getId()//会员
	   	     						 	,"您获得了收益:"+Arith.mul(order.getPayMoney(), agentConf.getTbpcPtZhj())//内容
	   	     						 	,new Date()//时间
	   	     							);
	   	                		msg2.save();
   	                	   }
   	                	account.update();
   	                	 if (member2.gettTop()!=null&&!member2.gettTop().equals("")) {
   	                		 Member member3=Member.where.uid(Long.parseLong(member2.gettTop())).get();//上上级
   	                		Account account2=Account.where.member(member3.getId()).get();
   	                		TbPartners agent2=TbPartners.where.tbpMember(member3.getId()).tbpBrand(order.getMerchant()).tbpPayCard((short)2).get();
   	                		Agent agentss=Agent.where.member(member3.getId()).merchant(order.getMerchant()).status((short)1).get();
   	   	                	
   	                		if (agent2!=null||agentss!=null) {//代理商
	   	                	 dljj=Arith.mul(order.getPayMoney(), agentConf.getTbpcDlJj());
	   	                		IncomeRecord incomeRecord=new IncomeRecord(
	   	                				agentss!=null?(short)2:(short)3//用户身份
	   	                				,(short)4//来源
	   	                			 	,(short)2//收益类型
	   	                			 	,Arith.mul(order.getPayMoney(), agentConf.getTbpcDlJj())//贡献收益
	   	                			 	,member.getHeader()//头像
	   	                			 	,member.getNickName()//姓名
	   	                			 	,member.getNickName()
   	                			 	,member3.getNickName()
	   	                			 	,member.getId()//贡献人
	   	                			 	,member3.getId()//收益人
	   	                			 	,order.getOrderNumber()//订单编号
	   	                			 	,order.getMerchant()//品牌信息
	   	                			 	,(short)2//结算情况
	   	                			 	,new Date()//修改时间 [非空]
	   	                			 	,new Date()//添加时间 [非空]
	   	                			 	,(short)1//状态 [非空]
	   	                			 	);
	   	                		incomeRecord.save();
	   	                		account2.setMoney(Arith.round(Arith.add(account2.getMoney(), Arith.mul(order.getPayMoney(), agentConf.getTbpcDlJj())), 2));
	   	                		TbMsg msg2=new TbMsg(
	   	                				member3.getId()//会员
	   	     						 	,"您获得了收益:"+Arith.mul(order.getPayMoney(), agentConf.getTbpcDlJj())//内容
	   	     						 	,new Date()//时间
	   	     							);
	   	                		msg2.save();	
   	                		}else {//普通分销员直接奖励
									 ptjj=Arith.mul(order.getPayMoney(), agentConf.getTbpcPtJj());
									IncomeRecord incomeRecord=new IncomeRecord(
											(short)1
		   	                				,(short)4//来源
		   	                			 	,(short)2//收益类型
		   	                			 	,Arith.mul(order.getPayMoney(), agentConf.getTbpcPtJj())//贡献收益
		   	                			 	,member.getHeader()//头像
		   	                			 	,member.getNickName()//姓名
		   	                			 	,member.getNickName()
   	                			 	,member3.getNickName()
		   	                			 	,member.getId()//贡献人
		   	                			 	,member3.getId()//收益人
		   	                			 	,order.getOrderNumber()//订单编号
		   	                			 	,order.getMerchant()//品牌信息
		   	                			 	,(short)2//结算情况
		   	                			 	,new Date()//修改时间 [非空]
		   	                			 	,new Date()//添加时间 [非空]
		   	                			 	,(short)1//状态 [非空]
		   	                			 	);
		   	                		incomeRecord.save();
		   	                		account2.setMoney(Arith.round(Arith.add(account2.getMoney(), Arith.mul(order.getPayMoney(), agentConf.getTbpcPtJj())), 2));
		   	                		TbMsg msg2=new TbMsg(
		   	                				member3.getId()//会员
		   	     						 	,"您获得了收益:"+Arith.mul(order.getPayMoney(), agentConf.getTbpcPtJj())//内容
		   	     						 	,new Date()//时间
		   	     							);
		   	                		msg2.save();	
   	                		}
	   	                	account2.update();
						}
   	                  }
   	               TbOrderInvoies  orderInvoies=new TbOrderInvoies(
   	            		order.getOrderNumber()//订单编号
 	             	 	,(short)4//来源
 	             	 	,order.getMerchant()//品牌商
 	             	 	,order.getMember()//购买人
 	             	 	,order.getPayMoney()//订单金额
 	             	 	,order.getPayMoney()//订单金额
 	             	 	,0.0
 	             	 	,0.0
 	             	 	,Arith.round(Arith.mul(configur.getProfitRatio(), order.getPayMoney()), 2)//平台收益
 	             	 	,ptjj//普通间接收益
 	             	 	,ptzj//普通直接收益
 	             	 	,dljj//代理间接收益
 	             	 	,dlzj//代理直接收益
 	             	 	,0.0//合伙人收益
 	             	 	,0.0//配送商收益
 	             	 	,0.0//经销商收益
 	             	 	,Arith.round(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(order.getPayMoney(), ptjj), ptzj),dljj),dlzj),Arith.mul(configur.getProfitRatio(), order.getPayMoney())), 2)//剩余收益
 	             	 	,new Date()//添加时间
	                		 );
	                 orderInvoies.save();
	                 BrandAccount brandAccount=BrandAccount.where.brand(order.getMerchant()).get();
	     			if (brandAccount==null) {
	     				BrandAccount bccount=new BrandAccount(
	     						order.getMerchant()//所属品牌 [非空]
	     					 	,orderInvoies.getTboiSySy()//总金额
	     					 	,orderInvoies.getTboiSySy()//累计收益
	     					 	,0.0//累计提现
	     					 	,new Date()//修改时间 [非空]
	     					 	,new Date()//添加时间 [非空]
	     					 	,(short)1//状态 [非空]
	     						);
	     				bccount.save();
	     			}else {
	     				brandAccount.setMoney(Arith.round(Arith.add(brandAccount.getMoney(), orderInvoies.getTboiSySy()), 2));
	     				brandAccount.setlSmoney(Arith.round(Arith.add(brandAccount.getlSmoney(), orderInvoies.getTboiSySy()), 2));
	     				brandAccount.update();
	     			}
					}
	   	               
   	                /**此处添加自己的业务逻辑代码end**/  
   	                //通知微信服务器已经支付成功  
   	                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
   	                + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";  
	   	            
	   	        //    }  
	   	        }else{  
	   	            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
	   	            + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
	   	        }  
	        }
	     
	      //  System.out.println(resXml);  
	       // System.out.println("微信支付回调数据结束");  
	  
	  
	        BufferedOutputStream out = new BufferedOutputStream(  
	                response.getOutputStream());  
	        out.write(resXml.getBytes());  
	        out.flush();  
	        out.close(); 
	}
	/**
	 * 测试代理卡购买回调
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/memberAgent/payAgentceshi.wx")
	public @title("测试代理卡购买回调") String payAgentceshi(
			@title("订单编号") String orderId
			)throws Exception{
		  
//           //验证签名是否正确  
//           if(PayUtil.verify(PayUtil.createLinkString(map), (String)map.get("sign"), WxPayConfig.key, "utf-8")){  
               /**此处添加自己的业务逻辑代码start**/  
             
              AgentCardOrder order=AgentCardOrder.where.orderNumber(orderId).get();
	//	   	            AgentCardOrder.where.id(order.getId()).payStatus(2,"<").set.payStatus((short)2).update();
              if (order.getPayStatus()==(short)1) {
               order.setPayStatus((short)2);
               order.update();//修改订单
               TbMsg msg=new TbMsg(
	                		order.getMember()//会员
						 	,"代理卡购买成功"//内容
						 	,new Date()//时间
							);
					msg.save();
         Member member=Member.where.uid(order.getMember()).get();
//               BrandFinance brandFinance=new BrandFinance(
//               		order.getMerchant()//品牌 [非空]
//                	 	,order.getPayMoney()//金额
//                	 	,(short)1//类型
//                	 	,(short)2//来源
//                	 	,order.getId()
//                	 	,configur.getProfitRatio()*order.getPayMoney()
//                	     ,new Date()//修改时间 [非空]
//	             	 	,new Date()//添加时间 [非空]
//	             	 	,(short)1//状态 [非空]
//               		);
//                brandFinance.save();
           Agent agenta=new Agent(
           		order.getMerchant()//所属品牌 [非空]
        	 	,order.getMember()//关联会员 [非空]
        	 	,member.getmTop()
   	            ,member.getmToptop()
        	 	,new Date()//修改时间 [非空]
        	 	,new Date()//添加时间 [非空]
        	 	,(short)1//状态 [非空]
           		);
              agenta.save();
              AgentConf agentConf=AgentConf.where.merchant(order.getMerchant()).get();
              if (agentConf!=null) {
			List<Products> aList=agentConf.get$products();
			if (aList.size()>0) {
				for (Products products : aList) {
					Commodity commodity=Commodity.where.id(products.getCommodity()).get();
					Product product=Product.where.member(member.getId()).merchant(order.getMerchant()).commodity(products.getCommodity()).get();
					if (product!=null) {
						product.setNumber(product.getNumber()+products.getNumber());
						product.update();
						ProductDetails productDetails=new ProductDetails(
								"代理卡购买赠送"//获得方式
							 	,order.getMerchant()//品牌信息
							 	,member.getId()//所属会员
							 	,products.getCommodity()//商品信息
							 	,commodity.getPrice()
							 	,products.getNumber()//数量
							 	,0
							 	,0
							 	,new Date()//获得时间 [非空]
							 	,(short)1//状态 [非空]
								);
						productDetails.save();
					}else {
						
						Product product2=new Product(
								commodity.getName()//名称 [非空]
							 	,order.getMerchant()//品牌信息
							 	,member.getUid$()
							 	,member.getId()//所属会员
							 	,products.getCommodity()//商品信息
							 	,commodity.getPrice()
				                ,commodity.getUnit$()
							 	,commodity.getImage()
							 	,products.getNumber()//数量
							 	,0
							 	,""//规格属性
							 	,0
							 	,"代理卡购买赠送"//来源描述
							 	,getThreeYear()
							 	,new Date()//修改时间 [非空]
							 	,new Date()//添加时间 [非空]
							 	,(short)1//状态 [非空]
								);
						product2.save();
						ProductDetails productDetails=new ProductDetails(
								"代理卡购买赠送"//获得方式
							 	,order.getMerchant()//品牌信息
							 	,member.getId()//所属会员
							 	,products.getCommodity()//商品信息
							 	,commodity.getPrice()
							 	,products.getNumber()//数量
							 	,0
							 	,0
							 	,new Date()//获得时间 [非空]
							 	,(short)1//状态 [非空]
								);
						productDetails.save();
					}
				}
			  }
			}
          }
        return "dsd";
	}
	/**
	 * 代理卡购买回调
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/memberAgent/payAgent.wx")
	public @title("代理卡购买回调") void payAgent(
			HttpServletRequest request,HttpServletResponse response
			)throws Exception{
		 BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));  
		  String line = null;  
	        StringBuilder sb = new StringBuilder();  
	        while((line = br.readLine()) != null){  
	            sb.append(line);  
	        }  
	        //sb为微信返回的xml  
	        String notityXml = sb.toString();  
	        String resXml = "";  
	        System.out.println("接收到的报文：是" + notityXml);  
	      
	        Map map = PayUtil.doXMLParse(notityXml);  
	         // System.out.println("返回ID"+map.get("out_trade_no"));
	        //  System.out.println("返回成功"+ map.get("return_code"));
	        if (map!=null){
	        	   String returnCode = (String) map.get("return_code");  
	   	        if("SUCCESS".equals(returnCode)){  
//	   	            //验证签名是否正确  
//	   	            if(PayUtil.verify(PayUtil.createLinkString(map), (String)map.get("sign"), WxPayConfig.key, "utf-8")){  
	   	                /**此处添加自己的业务逻辑代码start**/  
	   	                  String out_trade_no=(String) map.get("out_trade_no");
	   	              
	   	               AgentCardOrder order=AgentCardOrder.where.orderNumber(out_trade_no).get();
   	    	//	   	            AgentCardOrder.where.id(order.getId()).payStatus(2,"<").set.payStatus((short)2).update();
	   	               if (order.getPayStatus()==(short)1) {
	   	                order.setPayStatus((short)2);
   	                    order.update();//修改订单
   	                 Configur configur=Configur.where.get();
   	              Member member=Member.where.uid(order.getMember()).get();
//   	                    BrandFinance brandFinance=new BrandFinance(
//   	                    		order.getMerchant()//品牌 [非空]
//	   	                 	 	,order.getPayMoney()//金额
//	   	                 	 	,(short)1//类型
//	   	                 	 	,(short)2//来源
//	   	                 	 	,order.getId()
//	   	                 	 	,configur.getProfitRatio()*order.getPayMoney()
//	   	                 	     ,new Date()//修改时间 [非空]
//		   	             	 	,new Date()//添加时间 [非空]
//		   	             	 	,(short)1//状态 [非空]
//   	                    		);
//   	                     brandFinance.save();
   	                Agent agenta=new Agent(
   	                		order.getMerchant()//所属品牌 [非空]
   	             	 	,order.getMember()//关联会员 [非空]
   	             	 	,member.getmTop()
   	             	 	,member.getmToptop()
   	             	 	,new Date()//修改时间 [非空]
   	             	 	,new Date()//添加时间 [非空]
   	             	 	,(short)1//状态 [非空]
   	                		);
   	         
   	                   agenta.save();
   	                   AgentConf agentConf=AgentConf.where.merchant(order.getMerchant()).get();
   	                   if (agentConf!=null) {
						List<Products> aList=agentConf.get$products();
						if (aList.size()>0) {
							for (Products products : aList){
								Product product=Product.where.member(member.getId()).merchant(order.getMerchant()).commodity(products.getCommodity()).get();
								Commodity commodity=Commodity.where.id(Long.valueOf(products.getCommodity())).get();
								if (product!=null) {
									product.setNumber(product.getNumber()+products.getNumber());
									product.update();
									ProductDetails productDetails=new ProductDetails(
											"代理卡购买赠送"//获得方式
										 	,order.getMerchant()//品牌信息
										 	,member.getId()//所属会员
										 	,products.getCommodity()//商品信息
										 	,commodity.getPrice()
										 	,products.getNumber()//数量
										 	,0
										 	,0
										 	,new Date()//获得时间 [非空]
										 	,(short)1//状态 [非空]
											);
									productDetails.save();
								}else {
									Product product2=new Product(
											commodity.getName()//名称 [非空]
										 	,order.getMerchant()//品牌信息
										 	,member.getUid$()
										 	,member.getId()//所属会员
										 	,products.getCommodity()//商品信息
										 	,commodity.getPrice()
							                ,commodity.getUnit$()
										 	,commodity.getImage()
										 	,products.getNumber()//数量
										 	,0
										 	,""//规格属性
										 	,0
										 	,"代理卡购买赠送"//来源描述
										 	,getThreeYear()
										 	,new Date()//修改时间 [非空]
										 	,new Date()//添加时间 [非空]
										 	,(short)1//状态 [非空]
											);
									product2.save();
									ProductDetails productDetails=new ProductDetails(
											"代理卡购买赠送"//获得方式
										 	,order.getMerchant()//品牌信息
										 	,member.getId()//所属会员
										 	,products.getCommodity()//商品信息
										 	,commodity.getPrice()
										 	,products.getNumber()//数量
										 	,0
										 	,0
										 	,new Date()//获得时间 [非空]
										 	,(short)1//状态 [非空]
											);
									productDetails.save();
								}
							}
						}
					}
   	                Double ptjj=0.0;
   	                Double ptzj=0.0; 
   	                Double dljj=0.0;
	                Double dlzj=0.0;  
   	                  if(member.gettTop()!=null&&!member.gettTop().equals("")){//
   	                	 Member member2=Member.where.uid(Long.parseLong(member.gettTop())).get();//上级//39
   	                	Agent agent=Agent.where.member(member2.getId()).merchant(order.getMerchant()).status((short)1).get();
   	                	TbPartners agentas=TbPartners.where.tbpMember(member2.getId()).tbpBrand(order.getMerchant()).tbpPayCard((short)2).get();
   	                	Account account=Account.where.member(member2.getId()).get();
   	                	   if (agent!=null||agentas!=null) {//代理商
   	                		   dlzj=Arith.mul(order.getPayMoney(), agentConf.getDlZjJl());
   	                		IncomeRecord incomeRecord=new IncomeRecord(
   	                				agentas!=null?(short)3:(short)2
   	                				,(short)3//来源
   	                			 	,(short)1//收益类型
   	                			 	,Arith.mul(order.getPayMoney(), agentConf.getDlZjJl())//贡献收益
   	                			 	,member.getHeader()//头像
   	                			 	,member.getNickName()//姓名
   	                			 	,member.getNickName()
   	                			 	,member2.getNickName()
   	                			 	,member.getId()//贡献人
   	                			 	,member2.getId()//收益人
   	                			 	,order.getOrderNumber()//订单编号
   	                			 	,order.getMerchant()//品牌信息
   	                			 	,(short)2//结算情况
   	                			 	,new Date()//修改时间 [非空]
   	                			 	,new Date()//添加时间 [非空]
   	                			 	,(short)1//状态 [非空]
   	                			 	);
   	                		incomeRecord.save();
   	                		account.setMoney(Arith.round(Arith.add(account.getMoney(), Arith.mul(order.getPayMoney(), agentConf.getDlZjJl())), 2));
   	                		TbMsg msg2=new TbMsg(
   	                				member2.getId()//会员
   	     						 	,"您获得了收益:"+Arith.mul(order.getPayMoney(), agentConf.getDlZjJl())//内容
   	     						 	,new Date()//时间
   	     							);
   	                		msg2.save();	
							}else {//普通分销员
								ptzj=Arith.mul(order.getPayMoney(), agentConf.getFxZjJl());
								IncomeRecord incomeRecord=new IncomeRecord(
										(short)1
										,(short)3//来源
	   	                			 	,(short)1//收益类型
	   	                			 	,Arith.mul(order.getPayMoney(), agentConf.getFxZjJl())//贡献收益
	   	                			 	,member.getHeader()//头像
	   	                			 	,member.getNickName()//姓名
	   	                			 	,member.getNickName()
   	                			 	,member2.getNickName()
	   	                			 	,member.getId()//贡献人
	   	                			 	,member2.getId()//收益人
	   	                			 	,order.getOrderNumber()//订单编号
	   	                			 	,order.getMerchant()//品牌信息
	   	                			 	,(short)2//结算情况
	   	                			 	,new Date()//修改时间 [非空]
	   	                			 	,new Date()//添加时间 [非空]
	   	                			 	,(short)1//状态 [非空]
	   	                			 	);
	   	                		incomeRecord.save();
	   	                		account.setMoney(Arith.round(Arith.add(account.getMoney(), Arith.mul(order.getPayMoney(), agentConf.getFxZjJl())), 2));
	   	                		TbMsg msg2=new TbMsg(
	   	                				member2.getId()//会员
	   	     						 	,"您获得了收益:"+Arith.mul(order.getPayMoney(), agentConf.getFxZjJl())//内容
	   	     						 	,new Date()//时间
	   	     							);
	   	                		msg2.save();
							}
   	                	account.update();
   	                	 if (member2.gettTop()!=null&&!member2.gettTop().equals("")) {
   	                		 Member member3=Member.where.uid(Long.parseLong(member2.gettTop())).get();//上上级
   	                		Account account2=Account.where.member(member3.getId()).get();
   	                		Agent agent2=Agent.where.member(member3.getId()).merchant(order.getMerchant()).status((short)1).get();
   	                		TbPartners agentbs=TbPartners.where.tbpMember(member3.getId()).tbpBrand(order.getMerchant()).tbpPayCard((short)2).get();
   	   	                	
   	                		if (agent2!=null||agentbs!=null) {//代理商
	   	                	 dljj=Arith.mul(order.getPayMoney(), agentConf.getDlJjJl());
	   	                		IncomeRecord incomeRecord=new IncomeRecord(
	   	                				agentbs!=null?(short)3:(short)2
	   	                				,(short)3//来源
	   	                			 	,(short)2//收益类型
	   	                			 	,Arith.mul(order.getPayMoney(), agentConf.getDlJjJl())//贡献收益
	   	                			 	,member.getHeader()//头像
	   	                			 	,member.getNickName()//姓名
	   	                			 	,member.getNickName()
   	                			 	,member3.getNickName()
	   	                			 	,member.getId()//贡献人
	   	                			 	,member3.getId()//收益人
	   	                			 	,order.getOrderNumber()//订单编号
	   	                			 	,order.getMerchant()//品牌信息
	   	                			 	,(short)2//结算情况
	   	                			 	,new Date()//修改时间 [非空]
	   	                			 	,new Date()//添加时间 [非空]
	   	                			 	,(short)1//状态 [非空]
	   	                			 	);
	   	                		incomeRecord.save();
	   	                		account2.setMoney(Arith.round(Arith.add(account2.getMoney(), Arith.mul(order.getPayMoney(), agentConf.getDlJjJl())), 2));
	   	                		TbMsg msg2=new TbMsg(
	   	                				member3.getId()//会员
	   	     						 	,"您获得了收益:"+Arith.mul(order.getPayMoney(), agentConf.getDlJjJl())//内容
	   	     						 	,new Date()//时间
	   	     							);
	   	                		msg2.save();	
   	                		}else {//普通分销员直接奖励
									 ptjj=Arith.mul(order.getPayMoney(), agentConf.getFxJjJl());
									IncomeRecord incomeRecord=new IncomeRecord(
											(short)1
		   	                				,(short)3//来源
		   	                			 	,(short)2//收益类型
		   	                			 	,Arith.mul(order.getPayMoney(), agentConf.getFxJjJl())//贡献收益
		   	                			 	,member.getHeader()//头像
		   	                			 	,member.getNickName()//姓名
		   	                			 	,member.getNickName()
   	                			 	,member3.getNickName()
		   	                			 	,member.getId()//贡献人
		   	                			 	,member3.getId()//收益人
		   	                			 	,order.getOrderNumber()//订单编号
		   	                			 	,order.getMerchant()//品牌信息
		   	                			 	,(short)2//结算情况
		   	                			 	,new Date()//修改时间 [非空]
		   	                			 	,new Date()//添加时间 [非空]
		   	                			 	,(short)1//状态 [非空]
		   	                			 	);
		   	                		incomeRecord.save();
		   	                		account2.setMoney(Arith.round(Arith.add(account2.getMoney(), Arith.mul(order.getPayMoney(), agentConf.getFxJjJl())), 2));
		   	                		TbMsg msg2=new TbMsg(
		   	                				member3.getId()//会员
		   	     						 	,"您获得了收益:"+Arith.mul(order.getPayMoney(), agentConf.getFxJjJl())//内容
		   	     						 	,new Date()//时间
		   	     							);
		   	                		msg2.save();	
   	                		}
	   	                	account2.update();
						}
   	                  }
   	               TbOrderInvoies  orderInvoies=new TbOrderInvoies(
					    order.getOrderNumber()//订单编号
 	             	 	,(short)3//来源
 	             		,order.getMerchant()//品牌商
 	             	 	,order.getMember()//购买人
 	             	 	,order.getPayMoney()
 	             	 	,order.getPayMoney()//订单金额
 	             	 	,0.0
 	             	 	,0.0
 	             	 	,Arith.round(Arith.mul(configur.getProfitRatio(), order.getPayMoney()), 2)//平台收益
 	             	 	,ptjj//普通间接收益
 	             	 	,ptzj//普通直接收益
 	             	 	,dljj//代理间接收益
 	             	 	,dlzj//代理直接收益
 	             	 	,0.0//合伙人收益
 	             	 	,0.0//配送商收益
 	             	 	,0.0//经销商收益
 	             	 	,Arith.round(Arith.sub(Arith.sub(Arith.sub(Arith.sub(Arith.sub(order.getPayMoney(), ptjj), ptzj),dljj),dlzj),Arith.mul(configur.getProfitRatio(), order.getPayMoney())), 2)//剩余收益
 	             	 	,new Date()//添加时间
	                		 );
	                 orderInvoies.save();
	                 BrandAccount brandAccount=BrandAccount.where.brand(order.getMerchant()).get();
	     			if (brandAccount==null) {
	     				BrandAccount bccount=new BrandAccount(
	     						order.getMerchant()//所属品牌 [非空]
	     					 	,orderInvoies.getTboiSySy()//总金额
	     					 	,orderInvoies.getTboiSySy()//累计收益
	     					 	,0.0//累计提现
	     					 	,new Date()//修改时间 [非空]
	     					 	,new Date()//添加时间 [非空]
	     					 	,(short)1//状态 [非空]
	     						);
	     				bccount.save();
	     			}else {
	     				brandAccount.setMoney(Arith.round(Arith.add(brandAccount.getMoney(), orderInvoies.getTboiSySy()), 2));
	     				brandAccount.setlSmoney(Arith.round(Arith.add(brandAccount.getlSmoney(), orderInvoies.getTboiSySy()), 2));
	     				brandAccount.update();
	     			}
	     			 WechatMouldUtil wechatMouldUtil=new WechatMouldUtil();
						 Map<String, Object> data=new HashMap<String, Object>();
						 Map<String, Object> data1=new HashMap<String, Object>();
						data1.put("value", "代理卡购买成功");
						Map<String, Object> data2=new HashMap<String, Object>();
						data2.put("value", DateUtils.getTime());
						data.put("keyword1", data1);
						data.put("keyword2", data2);
                     wechatMouldUtil.sendWechatmsgToUser(order.getFormid(), "jl99X7ad0uB4HQrTJXWGSrFZblJEvgwHgDcNnN-v1Ls", member.getOpenid(), data);//发送微信小程序消息模板
   	                /**此处添加自己的业务逻辑代码end**/  
   	                //通知微信服务器已经支付成功  
   	                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"  
   	                + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";  
					}
	   	        //    }  
	   	        }else{  
	   	            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"  
	   	            + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";  
	   	        }  
	        }
	     
	      //  System.out.println(resXml);  
	       // System.out.println("微信支付回调数据结束");  
	  
	  
	        BufferedOutputStream out = new BufferedOutputStream(  
	                response.getOutputStream());  
	        out.write(resXml.getBytes());  
	        out.flush();  
	        out.close(); 
	}
	
	/**
	 * 会员购买合伙人卡定订单提交
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/api/memberAgent/hhrTOrder.do")
	public @title("会员购买合伙人卡定订单提交")  Protocol hhrTOrder(
			@title("姓名*") String name,
			@title("formId") String formId,
			@title("手机号") String mobile,
			@title("简介") String profile,
			@title("优势") String youshi,
			@title("纬度") String latitude,
			@title("经度") String longitude,
			@title("品牌商编号") Long banrdId,
			@title("地址编号") Long adressId
			) throws Exception{
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		Region region=Region.where.id(adressId).get();
		if (region.getLevel()!=4) {
			protocol.set("type", false);
			protocol.set("msg", "请选第四级地址");
			return protocol;
		}
		TbPartnerConfig agentConf=TbPartnerConfig.where.tbpcBrand(banrdId).get();
		if (agentConf==null) {
			protocol.set("type", false);
			protocol.set("msg", "合伙人卡未配置");
			return Protocol.create(false, "操作错误","not_found_user");
		}
		String orderNo=new Date().getTime()*3+"-"+member.getId()+"-"+agentConf.getTbpcId();
			TbPartnerCardOrder agentCardOrder=new TbPartnerCardOrder(
					orderNo
					,agentConf.getTbpcBrand()//所属品牌 [非空]
				 	,member.getId()//用户 [非空]
				 	,null//代理卡
				 	,formId
				 	,agentConf.getTbpcPrice()//支付金额 [非空]
				 	,new Date()//支付时间 [非空]
				 	,(short)1//支付状态 [非空]
				 	,new Date()//修改时间 [非空]
				 	,new Date()//添加时间 [非空]
				 	,(short)1//状态 [非空]
					);
			  agentCardOrder.save();
		
		TbPartnerCardOrder productOrde=TbPartnerCardOrder.where.orderNumber(orderNo).get();
		String pay_url=Utils.config("conf.wxpayurl");
		String notify_url=Utils.config("conf.host")+"/api/memberAgent/payHeHuoRen.wx";//回调接口地址
		
        //生成的随机字符串  
    	 String nonce_str = IpUtil.getRandomStringByLength(32); 
        //商品名称  
        String body = "合伙人卡购买";  
        //获取客户端的ip地址  
        String spbill_create_ip = IpUtil.getIpAddr(Utils.getServletRequest());
        System.out.println("真实IP地址"+spbill_create_ip);
        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        String money=decimalFormat.format(productOrde.getPayMoney()*100);
      //String spbill_create_ip = "127.0.0.1";
        //组装参数，用户生成统一下单接口的签名  
        Map<String, String> packageParams = new HashMap<String, String>();  
        packageParams.put("appid", Utils.config("wx.mp1.appid"));  
        packageParams.put("mch_id", Utils.config("wx.mch1.id"));  
        packageParams.put("nonce_str", nonce_str);  
        packageParams.put("body", body);  
        packageParams.put("out_trade_no", productOrde.getOrderNumber());//商户订单号  
        packageParams.put("total_fee", money);//支付金额，这边需要转成字符串类型，否则后面的签名会失败  
        packageParams.put("spbill_create_ip", spbill_create_ip);  
        packageParams.put("notify_url", notify_url);//支付成功后的回调地址  
        packageParams.put("trade_type", "JSAPI");//支付方式  
        packageParams.put("openid", member.getOpenid());  
             
            String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串   
          
            //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口  
            String mysign = PayUtil.sign(prestr, Utils.config("wx.mch1.key"), "utf-8").toUpperCase();  
          
        //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去  
        String xml = "<xml>" + "<appid>" +Utils.config("wx.mp1.appid") + "</appid>"   
                + "<body><![CDATA[" + body + "]]></body>"   
                + "<mch_id>" +  Utils.config("wx.mch1.id") + "</mch_id>"   
                + "<nonce_str>" + nonce_str + "</nonce_str>"   
                + "<notify_url>" + notify_url + "</notify_url>"   
                + "<openid>" + member.getOpenid() + "</openid>"   
                + "<out_trade_no>" + productOrde.getOrderNumber() + "</out_trade_no>"   
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"   
                + "<total_fee>" + money + "</total_fee>"  
                + "<trade_type>" + "JSAPI" + "</trade_type>"   
                + "<sign>" + mysign + "</sign>"  
                + "</xml>";  
          
        System.out.println("调试模式_统一下单接口 请求XML数据：" + xml);  
        //调用统一下单接口，并接受返回的结果  
        String result = PayUtil.httpRequest(pay_url, "POST", xml);  
        System.out.println("调试模式_统一下单接口 返回XML数据：" + result);  
        // 将解析结果存储在HashMap中     
        Map map = PayUtil.doXMLParse(result);  
        String return_code = (String) map.get("return_code");//返回状态码  
          
        System.out.println("调试模式_统一下F返回状态" + return_code);  
        if(return_code.equals("SUCCESS")){     
            String prepay_id = (String) map.get("prepay_id");//返回的预付单信息     
            protocol.set("nonceStr", nonce_str);  
            protocol.set("package", "prepay_id=" + prepay_id);  
            Long timeStamp = System.currentTimeMillis() / 1000;     
            protocol.set("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误  
            //拼接签名需要的参数  
            String stringSignTemp = "appId=" + Utils.config("wx.mp1.appid") + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;     
            //再次签名，这个签名用于小程序端调用wx.requesetPayment方法  
            String paySign = PayUtil.sign(stringSignTemp, Utils.config("wx.mch1.key"), "utf-8").toUpperCase();  
              
            protocol.set("paySign", paySign);  
            protocol.set("orderNo", orderNo);
            protocol.set("appid", Utils.config("wx.mp1.appid")); 
            protocol.set("type", true);
            protocol.setSuccess(true);
        }else {
        	 protocol.set("type", false);
        	protocol.setSuccess(false);
        	protocol.setMessage("支付失败");
		}  
		return protocol;
	}
	/**
	 * 会员购买代理卡定订单提交
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/api/memberAgent/agentTOrder.do")
	public @title("会员购买代理卡定订单提交")  Protocol agentTOrder(
			@title("formId") String formId,
			@title("代理卡") Long cardId
			
			) throws Exception{
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		AgentConf agentConf=AgentConf.where.id(cardId).get();
		if (agentConf==null) {
			protocol.set("type", 1);
			protocol.set("msg", "代理卡不存在");
			return Protocol.create(false, "操作错误","not_found_user");
		}
		AgentCardOrder agentCardOrder=AgentCardOrder.where.member(member.getId()).agentCard(cardId).get();
		String orderNo=new Date().getTime()*3+"-"+member.getId()+"-"+agentConf.getId();
		if (agentCardOrder==null) {
			agentCardOrder=new AgentCardOrder(
					orderNo
					,agentConf.getMerchant()//所属品牌 [非空]
					,member.getUid$()
				 	,member.getId()//用户 [非空]
				 	,agentConf.getId()//代理卡
				 	,formId
				 	,agentConf.getPrice()//支付金额 [非空]
				 	,new Date()//支付时间 [非空]
				 	,(short)1//支付状态 [非空]
				 	,new Date()//修改时间 [非空]
				 	,new Date()//添加时间 [非空]
				 	,(short)1//状态 [非空]
					);
			  agentCardOrder.save();
		}else {
			agentCardOrder.setOrderNumber(orderNo);
			agentCardOrder.update();
		}
		
		AgentCardOrder productOrde=AgentCardOrder.where.orderNumber(orderNo).get();
		String pay_url=Utils.config("conf.wxpayurl");
		String notify_url=Utils.config("conf.host")+"/api/memberAgent/payAgent.wx";//回调接口地址
		
        //生成的随机字符串  
    	 String nonce_str = IpUtil.getRandomStringByLength(32); 
        //商品名称  
        String body = "代理卡购买";  
        //获取客户端的ip地址  
        String spbill_create_ip = IpUtil.getIpAddr(Utils.getServletRequest());
        System.out.println("真实IP地址"+spbill_create_ip);
        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        String money=decimalFormat.format(productOrde.getPayMoney()*100);
      //String spbill_create_ip = "127.0.0.1";
        //组装参数，用户生成统一下单接口的签名  
        Map<String, String> packageParams = new HashMap<String, String>();  
        packageParams.put("appid", Utils.config("wx.mp1.appid"));  
        packageParams.put("mch_id", Utils.config("wx.mch1.id"));  
        packageParams.put("nonce_str", nonce_str);  
        packageParams.put("body", body);  
        packageParams.put("out_trade_no", productOrde.getOrderNumber());//商户订单号  
        packageParams.put("total_fee", money);//支付金额，这边需要转成字符串类型，否则后面的签名会失败  
        packageParams.put("spbill_create_ip", spbill_create_ip);  
        packageParams.put("notify_url", notify_url);//支付成功后的回调地址  
        packageParams.put("trade_type", "JSAPI");//支付方式  
        packageParams.put("openid", member.getOpenid());  
             
            String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串   
          
            //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口  
            String mysign = PayUtil.sign(prestr, Utils.config("wx.mch1.key"), "utf-8").toUpperCase();  
          
        //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去  
        String xml = "<xml>" + "<appid>" +Utils.config("wx.mp1.appid") + "</appid>"   
                + "<body><![CDATA[" + body + "]]></body>"   
                + "<mch_id>" +  Utils.config("wx.mch1.id") + "</mch_id>"   
                + "<nonce_str>" + nonce_str + "</nonce_str>"   
                + "<notify_url>" + notify_url + "</notify_url>"   
                + "<openid>" + member.getOpenid() + "</openid>"   
                + "<out_trade_no>" + productOrde.getOrderNumber() + "</out_trade_no>"   
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"   
                + "<total_fee>" + money + "</total_fee>"  
                + "<trade_type>" + "JSAPI" + "</trade_type>"   
                + "<sign>" + mysign + "</sign>"  
                + "</xml>";  
          
        System.out.println("调试模式_统一下单接口 请求XML数据：" + xml);  
        //调用统一下单接口，并接受返回的结果  
        String result = PayUtil.httpRequest(pay_url, "POST", xml);  
        System.out.println("调试模式_统一下单接口 返回XML数据：" + result);  
        // 将解析结果存储在HashMap中     
        Map map = PayUtil.doXMLParse(result);  
        String return_code = (String) map.get("return_code");//返回状态码  
          
        System.out.println("调试模式_统一下F返回状态" + return_code);  
        if(return_code.equals("SUCCESS")){     
            String prepay_id = (String) map.get("prepay_id");//返回的预付单信息     
            protocol.set("nonceStr", nonce_str);  
            protocol.set("package", "prepay_id=" + prepay_id);  
            Long timeStamp = System.currentTimeMillis() / 1000;     
            protocol.set("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误  
            //拼接签名需要的参数  
            String stringSignTemp = "appId=" + Utils.config("wx.mp1.appid") + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;     
            //再次签名，这个签名用于小程序端调用wx.requesetPayment方法  
            String paySign = PayUtil.sign(stringSignTemp, Utils.config("wx.mch1.key"), "utf-8").toUpperCase();  
              
            protocol.set("paySign", paySign);  
            protocol.set("appid", Utils.config("wx.mp1.appid")); 
            protocol.set("type", 2);
            protocol.setSuccess(true);
        }else {
        	 protocol.set("type", 3);
        	protocol.setSuccess(false);
        	protocol.setMessage("支付失败");
		}  
		return protocol;
	}
}
